package com.sqy.exception;

import com.sqy.utlis.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {

      private  final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public  Object  handleException(Exception e){
        log.error("Default Exception: ",e);
        return ApiResult.error(ImoocMallExceptionEnum.SYSTEM_ERROR);
    }






    @ExceptionHandler(ImoocMallException.class)
    @ResponseBody
    public  Object  ImoocMallException(ImoocMallException e){
        log.error("ImoocMallException Exception: ",e);
        return ApiResult.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public  ApiResult  handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException: ",e);
        return handleBindingResult(e.getBindingResult());
    }

     private  ApiResult handleBindingResult(BindingResult result){

         List<String> list=new ArrayList<>();
         if(result.hasErrors()){
             List<ObjectError> allErrors = result.getAllErrors();
             for (int i = 0; i <allErrors.size() ; i++) {
                 ObjectError objectError = allErrors.get(i);
                 String defaultMessage = objectError.getDefaultMessage();
                 list.add(defaultMessage);
             }
         }

         if(list.size()==0){
             return  ApiResult.error(ImoocMallExceptionEnum.REQUEST_PARAE);
         }

         return  ApiResult.error(ImoocMallExceptionEnum.REQUEST_PARAE.getCode(),list.toString());
     }
}
